$(document).ready(function() {
    // 从 localStorage 获取玩家信息
    const playerData = localStorage.getItem('player');
    if (playerData) {
        const player = JSON.parse(playerData);
        $('#playerName').text(player.username);
    } else {
        window.location.href = '/login';
        return;
    }
    
    // 加载房间列表
    loadRoomList();
    
    // 绑定创建房间按钮事件
    $('#createRoom').click(function() {
        createRoom();
    });
    
    // 绑定刷新按钮事件
    $('#refreshRooms').click(function() {
        loadRoomList();
    });

    // 绑定房间过滤事件
    $('#roomFilter').change(function() {
        filterRooms();
    });

    // 绑定房间搜索事件
    $('#roomSearch').on('input', function() {
        filterRooms();
    });

    // 初始化音频管理器
    AudioManager.init();

    // 在 document.ready 中添加事件绑定
    $('#createAIRoom').click(function() {
        createAIRoom();
    });
});

function loadRoomList() {
    $.get('/api/game/rooms')
        .done(function(rooms) {
            displayRooms(rooms);
        })
        .fail(function(error) {
            ErrorHandler.handleError(error, '加载房间列表失败');
        });
}

function displayRooms(rooms) {
    const roomList = $('#roomList');
    roomList.empty();
    
    if (rooms.length === 0) {
        roomList.append('<div class="col-12 text-center">暂无可用房间</div>');
        return;
    }
    
    rooms.forEach(room => {
        const roomCard = `
            <div class="col-md-4 mb-4">
                <div class="game-card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">${room.roomName}</h5>
                        <span class="status-badge ${getStatusClass(room.status)}">
                            ${getStatusText(room.status)}
                        </span>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="player-count">
                                <i class="fas fa-users me-2"></i>${room.playerCount}/3
                            </span>
                            <button class="btn btn-primary join-room" 
                                    data-room-id="${room.id}"
                                    ${room.playerCount >= 3 || room.status !== 'WAITING' ? 'disabled' : ''}>
                                <i class="fas fa-sign-in-alt me-1"></i>加入
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        roomList.append(roomCard);
    });
    
    // 绑定加入房间按钮事件
    $('.join-room').click(function() {
        const roomId = $(this).data('room-id');
        joinRoom(roomId);
    });

    filterRooms();
}

function getStatusClass(status) {
    switch(status) {
        case 'WAITING': return 'status-waiting';
        case 'PLAYING': return 'status-playing';
        default: return '';
    }
}

function getStatusText(status) {
    switch(status) {
        case 'WAITING': return '等待中';
        case 'PLAYING': return '游戏中';
        case 'FINISHED': return '已结束';
        case 'CLOSED': return '已关闭';
        default: return status;
    }
}

function createRoom() {
    const playerData = localStorage.getItem('player');
    if (!playerData) {
        MessageUI.showMessage('请先登录', 'error');
        return;
    }
    
    const player = JSON.parse(playerData);
    
    $.ajax({
        url: '/api/game/rooms',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            id: player.id,
            username: player.username
        })
    })
    .done(function(room) {
        joinRoom(room.id);
    })
    .fail(function(error) {
        ErrorHandler.handleError(error, '创建房间失败');
    });
}

function joinRoom(roomId) {
    const playerData = localStorage.getItem('player');
    if (!playerData) {
        MessageUI.showMessage('请先登录', 'error');
        return;
    }
    
    const player = JSON.parse(playerData);
    
    $.ajax({
        url: `/api/game/rooms/${roomId}/join`,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            id: player.id,
            username: player.username
        })
    })
    .done(function(room) {
        window.location.href = `/game?roomId=${roomId}`;
    })
    .fail(function(error) {
        ErrorHandler.handleError(error, '加入房间失败');
    });
}

function filterRooms() {
    const filterValue = $('#roomFilter').val();
    const searchText = $('#roomSearch').val().toLowerCase();
    
    $('.game-card').each(function() {
        const card = $(this);
        const status = card.find('.status-badge').text().trim();
        const roomName = card.find('.card-title').text().toLowerCase();
        
        let show = true;
        
        // 应用状态过滤
        if (filterValue !== 'all') {
            show = status === getStatusText(filterValue);
        }
        
        // 应用搜索过滤
        if (show && searchText) {
            show = roomName.includes(searchText);
        }
        
        card.parent().toggle(show);
    });
}

// 自动刷新房间列表
setInterval(loadRoomList, 5000);

// 添加创建AI房间的函数
function createAIRoom() {
    const playerData = localStorage.getItem('player');
    if (!playerData) {
        MessageUI.showMessage('请先登录', 'error');
        return;
    }
    
    const player = JSON.parse(playerData);
    
    $.ajax({
        url: '/api/game/rooms/ai',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            id: player.id,
            username: player.username
        })
    })
    .done(function(room) {
        joinRoom(room.id);
    })
    .fail(function(error) {
        ErrorHandler.handleError(error, '创建AI房间失败');
    });
}